<template>
  <!-- 直接使用两个独立元素，而不是嵌套结构 -->
  <!-- 悬浮机器人图标 -->
  <div class="ai-chat-button" :class="{ dark: isDark }" @click="toggleChatbox" ref="robotButton">
    <img src="@/assets/robot.svg" alt="AI助手" />
    <div v-if="unreadMessages > 0" class="notification-badge">{{ unreadMessages }}</div>
  </div>

  <!-- 聊天界面 -->
  <div class="chat-container" :class="{ dark: isDark }" v-show="showChatbox">
    <div class="sidebar">
      <div class="history-header">
        <h2>聊天记录</h2>
        <button class="new-chat" @click="startNewChat">
          <PlusIcon class="icon" />
          新对话
        </button>
      </div>
      <div class="history-list">
        <div
          v-for="chat in chatHistory"
          :key="chat.chatId"
          class="history-item"
          :class="{ active: currentChatId === chat.chatId }"
          @click="loadChat(chat.chatId)"
        >
          <ChatBubbleLeftRightIcon class="icon" />
          <span class="title">{{ chat.title || "新对话" }}</span>
        </div>
      </div>
    </div>

    <div class="chat-main">
      <div class="chat-header">
        <h2>智能助手</h2>
        <div class="header-actions">
          <button class="header-btn" @click="clearChat">
            <TrashIcon class="icon" />
          </button>
          <button class="header-btn" @click="toggleChatbox">
            <XMarkIcon class="icon" />
          </button>
        </div>
      </div>
      <div class="messages" ref="messagesRef">
        <div
          v-for="(message, index) in currentMessages"
          :key="index"
          :class="['message', message.role === 'user' ? 'user-message' : 'assistant-message']"
        >
          <div class="message-content" v-html="message.content"></div>
        </div>
      </div>

      <div class="input-area">
        <div class="input-row">
          <textarea
            v-model="userInput"
            @input="adjustTextareaHeight"
            @keydown.enter.prevent="sendMessage"
            placeholder="输入消息..."
            rows="1"
            ref="inputRef"
          ></textarea>
          <button class="send-button" @click="sendMessage" :disabled="isStreaming || !userInput.trim()">
            <PaperAirplaneIcon class="icon" />
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from "vue";
import { useDark } from "@vueuse/core";
import { ChatBubbleLeftRightIcon, PaperAirplaneIcon, PlusIcon, XMarkIcon, TrashIcon } from "@heroicons/vue/24/outline";
import { formatToLocalDateTime } from "@/utils/date";
import { sendChatMessage, getChatHistory, getChatMessages, clearChatHistory } from "@/api/ai";
import { ElMessage } from "element-plus";

const isDark = useDark();
const messagesRef = ref(null);
const inputRef = ref(null);
const robotButton = ref(null);
const userInput = ref("");
const isStreaming = ref(false);
const currentChatId = ref(null);
const currentMessages = ref([]);
const chatHistory = ref([]);
const showChatbox = ref(false);
const unreadMessages = ref(0);

// 自动调整输入框高度
const adjustTextareaHeight = () => {
  const textarea = inputRef.value;
  if (textarea) {
    textarea.style.height = "auto";
    const scrollHeight = textarea.scrollHeight;
    textarea.style.height = scrollHeight + "px";
  }
};

// 修改监听逻辑，确保在值变化时调整高度
watch(userInput, () => {
  nextTick(() => {
    adjustTextareaHeight();
  });
});

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight;
  }
};

// 切换聊天框显示状态
const toggleChatbox = async () => {
  // 只在首次打开时加载聊天历史
  if (!showChatbox.value && chatHistory.value.length === 0) {
    await loadChatHistory();
  }
  currentChatId.value = chatHistory.value[0]?.chatId;
  await loadChat(currentChatId.value);
  showChatbox.value = !showChatbox.value;
  if (showChatbox.value) {
    unreadMessages.value = 0;
    nextTick(() => {
      scrollToBottom();
    });
  }
};

// 发送消息
const sendMessage = async () => {
  if (isStreaming.value || !userInput.value.trim()) return;

  // 添加用户消息
  const userMessage = {
    role: "user",
    content: userInput.value.trim(),
  };
  currentMessages.value.push(userMessage);

  // 清空输入框
  const userQuery = userInput.value;
  userInput.value = "";
  adjustTextareaHeight();
  await scrollToBottom();

  // 准备发送数据
  const formData = new FormData();
  formData.append("prompt", userQuery);

  // 添加助手消息占位
  const assistantMessage = {
    role: "assistant",
    content: "",
    isStreaming: true,
  };
  currentMessages.value.push(assistantMessage);
  isStreaming.value = true;

  try {
    const response = await sendChatMessage(userQuery, currentChatId.value);
    const reader = response.body.getReader();
    const decoder = new TextDecoder("utf-8");

    // 字符逐个显示的计时器
    let buffer = "";
    let displayedContent = "";
    let typingTimer = null;

    // 模拟打字效果
    const typeCharacter = () => {
      if (buffer.length > 0) {
        // 取出缓冲区的第一个字符
        const char = buffer.charAt(0);
        buffer = buffer.substring(1);

        // 更新显示内容
        displayedContent += char;
        assistantMessage.content = formatResponseContent(displayedContent);

        // 强制更新视图
        currentMessages.value = [...currentMessages.value];
        scrollToBottom();

        // 设置下一个字符的显示时间（根据字符类型调整速度，但更快）
        const delay = /[,.!?;:]/.test(char) ? 50 : 15;
        typingTimer = setTimeout(typeCharacter, delay);
      } else {
        // 缓冲区空了，但可能还有更多数据到来
        if (!assistantMessage.isStreaming) {
          clearTimeout(typingTimer);
        }
      }
    };

    while (true) {
      try {
        const { value, done } = await reader.read();
        if (done) {
          // 流结束，标记消息不再流式显示
          assistantMessage.isStreaming = false;
          break;
        }

        // 解码并添加到缓冲区
        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;

        // 如果还没有开始打字，则开始
        if (!typingTimer) {
          typeCharacter();
        }
      } catch (readError) {
        console.error("读取流错误:", readError);
        assistantMessage.isStreaming = false;
        break;
      }
    }

    // 确保所有内容都已显示
    while (buffer.length > 0) {
      await new Promise((resolve) => setTimeout(resolve, 50));
    }

    // 如果聊天框未显示，增加未读消息数
    if (!showChatbox.value) {
      unreadMessages.value++;
    }
    // 更新标题
    loadChatHistory();
  } catch (error) {
    console.error("发送消息失败:", error);
    assistantMessage.content = "抱歉，发生了错误，请稍后重试。";
    assistantMessage.isStreaming = false;
  } finally {
    isStreaming.value = false;
    await scrollToBottom();
    // 如果是新对话，添加到历史记录
    if (!currentChatId.value) {
      const newChatId = Date.now().toString();
      currentChatId.value = newChatId;
      chatHistory.value = [{ id: newChatId, title: `对话 ${newChatId.slice(-6)}` }, ...chatHistory.value];
    }
  }
};

// 加载特定对话
const loadChat = async (chatId) => {
  console.log("加载对话:", chatId);
  currentChatId.value = chatId;
  try {
    const response = await getChatMessages(chatId);
    if (response.success && response.data) {
      // 对每条消息内容应用格式化处理
      currentMessages.value = response.data.map(message => ({
        ...message,
        content: message.role === 'assistant' ? formatResponseContent(message.content) : message.content
      }));
      console.log("加载对话消息成功:", currentMessages.value);
    } else {
      currentMessages.value = [];
    }
    await scrollToBottom();
  } catch (error) {
    console.error("加载对话消息失败:", error);
    currentMessages.value = [];
  }
};

// 加载聊天历史
const loadChatHistory = async () => {
  try {
    const response = await getChatHistory();
    if (response.success && response.data) {
      chatHistory.value = response.data;
      // 如果为空，添加一个默认的对话
      if (chatHistory.value.length === 0) {
        startNewChat();
      }
      // 自动加载第一个对话
      if (currentChatId.value === null && chatHistory.value.length > 0) {
        await loadChat(chatHistory.value[0].chatId);
      }
    } else {
      // 如果API失败，创建一个新对话
      const newChatId = Date.now().toString();
      chatHistory.value = [{ chatId: newChatId, title: `对话 ${newChatId.slice(-6)}` }];
      currentChatId.value = newChatId;
      currentMessages.value = [
        {
          role: "assistant",
          content: formatResponseContent("您好！我是您的智能助手，有什么可以帮您的吗？"),
        },
      ];
    }
  } catch (error) {
    console.error("加载聊天历史失败:", error);
    // 出错时创建一个新对话
    const newChatId = Date.now().toString();
    chatHistory.value = [{ chatId: newChatId, title: `对话 ${newChatId.slice(-6)}` }];
    currentChatId.value = newChatId;
    currentMessages.value = [
      {
        role: "assistant",
        content: formatResponseContent("您好！我是您的智能助手，有什么可以帮您的吗？"),
      },
    ];
  }
};

// 开始新对话
const startNewChat = async () => {
  // 判断会话数量是否超出上限
  if (chatHistory.value.length >= 10) {
    ElMessage.error("会话数量已达到上限，请先清空一些对话。");
    return;
  }
  // 创建一个新的聊天ID
  const newChatId = Date.now().toString();

  // 清除当前对话ID，重置为新ID
  currentChatId.value = newChatId;

  // 重置消息列表，添加欢迎消息
  currentMessages.value = [
    {
      role: "assistant",
      content: formatResponseContent("您好！我是您的智能助手，有什么可以帮您的吗？"),
    },
  ];

  // 将新对话添加到历史记录列表的开头
  chatHistory.value = [{ chatId: newChatId, title: `对话 ${newChatId.slice(-6)}` }, ...chatHistory.value];

  // 滚动到底部以显示欢迎消息
  await nextTick();
  scrollToBottom();

  // 确保聊天框是打开的
  if (!showChatbox.value) {
    showChatbox.value = true;
  }
};

// 清空聊天记录
const clearChat = async () => {
  try {
    // 获取当前会话ID
    const chatId = currentChatId.value;
    if (!chatId) {
      ElMessage.error("请选择要清空的对话");
      return;
    }
    if (chatHistory.value.length === 1) {
      ElMessage.error("无法清空唯一对话");
      return;
    }
    await clearChatHistory(chatId);
    chatHistory.value = chatHistory.value.filter((chat) => chat.chatId !== chatId);
    currentChatId.value = chatHistory.value[0]?.chatId;
    await loadChat(currentChatId.value);
  } catch (error) {
    console.error("清空当前聊天失败:", error);
  }
};

// 格式化响应内容，处理特殊标记
const formatResponseContent = (text) => {
  // 清理文本中可能的HTML标签
  let cleanText = text
    .replace(/<\/?[^>]+(>|$)/g, "") // 移除HTML标签
    .trim();

  // 处理特殊字符
  cleanText = cleanText
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&apos;/g, "'")
    .replace(/&amp;/g, "&");

  // 处理代码块 (必须在其他处理之前)
  cleanText = cleanText.replace(/```([\s\S]*?)```/g, (match, codeContent) => {
    return `<pre><code>${codeContent.trim()}</code></pre>`;
  });

  // 处理Markdown表格
  cleanText = processMarkdownTables(cleanText);

  // 处理标题
  cleanText = cleanText
    .replace(/^### (.*?)$/gm, '<h3>$1</h3>')
    .replace(/^## (.*?)$/gm, '<h2>$1</h2>')
    .replace(/^# (.*?)$/gm, '<h1>$1</h1>');

  // 处理列表
  cleanText = cleanText
    .replace(/^\s*\d+\.\s+(.*?)$/gm, '<li>$1</li>')
    .replace(/<\/li>\n<li>/g, '</li><li>')
    .replace(/(<li>.*?<\/li>)/gs, '<ol>$1</ol>')
    .replace(/^\s*[-*]\s+(.*?)$/gm, '<li>$1</li>')
    .replace(/<\/li>\n<li>/g, '</li><li>')
    .replace(/(<li>.*?<\/li>)/gs, '<ul>$1</ul>');

  // 处理链接
  cleanText = cleanText.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');

  // 处理图片
  cleanText = cleanText.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" class="markdown-image">');

  // 处理引用
  cleanText = cleanText.replace(/^>\s+(.*?)$/gm, '<blockquote>$1</blockquote>');
  
  // 处理分隔线
  cleanText = cleanText.replace(/^---+$/gm, '<hr>');

  // 处理行内代码
  cleanText = cleanText.replace(/`([^`]+)`/g, '<code>$1</code>');

  // 处理粗体和斜体
  cleanText = cleanText
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
    .replace(/\*([^*]+)\*/g, '<em>$1</em>')
    .replace(/_([^_]+)_/g, '<em>$1</em>');

  // 处理换行
  cleanText = cleanText.replace(/\n/g, '<br>');

  return cleanText;
};

// 处理Markdown表格
const processMarkdownTables = (text) => {
  // 匹配整个表格块
  const tableRegex = /(\|[^\n]+\|\n)((?:\|[-:]+[-| :]*\|\n))((?:\|[^\n]+\|\n)+)/g;
  
  return text.replace(tableRegex, (match, headerRow, separatorRow, bodyRows) => {
    // 处理表头
    const headers = headerRow
      .trim()
      .split('|')
      .filter(cell => cell.trim() !== '')
      .map(cell => `<th>${cell.trim()}</th>`)
      .join('');
    
    // 处理表格内容
    const rows = bodyRows
      .trim()
      .split('\n')
      .map(row => {
        const cells = row
          .trim()
          .split('|')
          .filter(cell => cell.trim() !== '')
          .map(cell => `<td>${cell.trim()}</td>`)
          .join('');
        
        return `<tr>${cells}</tr>`;
      })
      .join('');
    
    // 返回HTML表格
    return `<div class="table-container"><table class="markdown-table"><thead><tr>${headers}</tr></thead><tbody>${rows}</tbody></table></div>`;
  });
};

onMounted(async () => {
  await loadChatHistory();
  adjustTextareaHeight();
});
</script>

<style scoped>
.ai-chat-button {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 1001;
  border: 2px solid #e6e6e6;
  overflow: hidden;
  user-select: none;
  transition: transform 0.3s;
}

.ai-chat-button:hover {
  transform: scale(1.05);
}

.ai-chat-button img {
  width: 40px;
  height: 40px;
}

.notification-badge {
  position: absolute;
  top: 0;
  right: 0;
  background-color: #f56c6c;
  color: white;
  border-radius: 50%;
  min-width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.chat-container {
  position: fixed;
  bottom: 20px;
  right: 80px;
  width: 800px;
  height: 600px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  display: flex;
  overflow: hidden;
  z-index: 1000;
}

.sidebar {
  width: 250px;
  background: #f5f7fa;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
}

.history-header {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.new-chat {
  background: #38a7ff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  font-size: 14px;
}

.new-chat .icon {
  width: 16px;
  height: 16px;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.history-item {
  padding: 10px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  margin-bottom: 6px;
}

.history-item.active {
  background: rgba(56, 167, 255, 0.1);
}

.history-item:hover:not(.active) {
  background: rgba(0, 0, 0, 0.05);
}

.history-item .icon {
  width: 18px;
  height: 18px;
  color: #38a7ff;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  padding: 16px;
  background: #38a7ff;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.header-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.header-btn .icon {
  width: 20px;
  height: 20px;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 12px;
  position: relative;
}

.user-message {
  align-self: flex-end;
  background-color: #38a7ff;
  color: white;
}

.assistant-message {
  align-self: flex-start;
  background-color: #f5f7fa;
  color: #333;
  border: 1px solid #ebeef5;
}

.message-content {
  line-height: 1.5;
  word-break: break-word;
}

.message-content :deep(h1),
.message-content :deep(h2),
.message-content :deep(h3) {
  margin-top: 16px;
  margin-bottom: 8px;
  font-weight: 600;
  line-height: 1.25;
}

.message-content :deep(h1) {
  font-size: 1.5em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 0.3em;
}

.message-content :deep(h2) {
  font-size: 1.3em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 0.3em;
}

.message-content :deep(h3) {
  font-size: 1.1em;
}

.message-content :deep(ul),
.message-content :deep(ol) {
  padding-left: 2em;
  margin: 0.5em 0;
}

.message-content :deep(ul) {
  list-style-type: disc;
}

.message-content :deep(ol) {
  list-style-type: decimal;
}

.message-content :deep(li) {
  margin: 0.25em 0;
}

.message-content :deep(a) {
  color: #0366d6;
  text-decoration: none;
}

.message-content :deep(a:hover) {
  text-decoration: underline;
}

.message-content :deep(blockquote) {
  margin: 0.5em 0;
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
}

.message-content :deep(hr) {
  height: 0.25em;
  padding: 0;
  margin: 24px 0;
  background-color: #e1e4e8;
  border: 0;
}

.message-content :deep(.markdown-image) {
  max-width: 100%;
  margin: 8px 0;
  border-radius: 4px;
}

.message-content :deep(code) {
  background-color: rgba(0, 0, 0, 0.1);
  padding: 2px 4px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 0.9em;
}

.message-content :deep(pre) {
  margin: 8px 0;
  background-color: rgba(0, 0, 0, 0.05);
  padding: 16px;
  border-radius: 4px;
  overflow-x: auto;
}

.message-content :deep(pre code) {
  background-color: transparent;
  padding: 0;
  border-radius: 0;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 0.9em;
  line-height: 1.6;
  white-space: pre;
}

.dark .message-content :deep(h1),
.dark .message-content :deep(h2) {
  border-bottom-color: #444;
}

.dark .message-content :deep(blockquote) {
  color: #a0a0a0;
  border-left-color: #444;
}

.dark .message-content :deep(hr) {
  background-color: #444;
}

.dark .message-content :deep(a) {
  color: #58a6ff;
}

.message-content :deep(.table-container) {
  overflow-x: auto;
  margin: 16px 0;
}

.message-content :deep(.markdown-table) {
  border-collapse: collapse;
  width: 100%;
  margin: 8px 0;
}

.message-content :deep(.markdown-table th),
.message-content :deep(.markdown-table td) {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.message-content :deep(.markdown-table th) {
  background-color: rgba(0, 0, 0, 0.05);
  font-weight: bold;
}

.message-content :deep(.markdown-table tr:nth-child(even)) {
  background-color: rgba(0, 0, 0, 0.02);
}

.dark .message-content :deep(.markdown-table th),
.dark .message-content :deep(.markdown-table td) {
  border-color: #444;
}

.dark .message-content :deep(.markdown-table th) {
  background-color: rgba(255, 255, 255, 0.1);
}

.dark .message-content :deep(.markdown-table tr:nth-child(even)) {
  background-color: rgba(255, 255, 255, 0.05);
}

.message-time {
  display: none;
}

.input-area {
  padding: 16px;
  border-top: 1px solid #ebeef5;
}

.input-row {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  background: #f5f7fa;
  border-radius: 24px;
  padding: 8px 16px;
  margin-bottom: 0;
}

textarea {
  flex: 1;
  border: none;
  background: transparent;
  resize: none;
  padding: 12px 0;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.5;
  max-height: 150px;
  min-height: 24px;
  outline: none;
  overflow-y: hidden;
}

.send-button {
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #38a7ff;
  color: white;
  border: none;
  cursor: pointer;
  transition: all 0.2s ease;
}

.send-button:hover:not(:disabled) {
  background: #2490e8;
  transform: translateY(-2px);
}

.send-button .icon {
  width: 20px;
  height: 20px;
}

.send-button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 深色模式 */
.dark.chat-container {
  background: #1e1e1e;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.dark .sidebar {
  background: #2c2c2c;
  border-right-color: #333;
}

.dark .history-header {
  border-bottom-color: #333;
}

.dark .history-header h2 {
  color: #fff;
}

.dark .chat-header {
  background: #2c2c2c;
}

.dark .history-item:hover:not(.active) {
  background: rgba(255, 255, 255, 0.1);
}

.dark .assistant-message {
  background: #2c2c2c;
  color: #eee;
  border-color: #333;
}

.dark .input-area {
  border-top-color: #333;
}

.dark .input-row {
  background: #2c2c2c;
}

.dark textarea {
  color: #eee;
}

.dark textarea::placeholder {
  color: #999;
}

.dark.ai-chat-button {
  background: #2c2c2c;
  border-color: #444;
}

@media (max-width: 850px) {
  .chat-container {
    width: 90vw;
    right: 5vw;
  }

  .sidebar {
    width: 200px;
  }
}

@media (max-width: 600px) {
  .chat-container {
    width: 100vw;
    height: 80vh;
    bottom: 80px;
    right: 0;
    border-radius: 16px 16px 0 0;
  }

  .sidebar {
    display: none;
  }
}
</style>
